import React, {useCallback, useState} from 'react';
import style from './BookDetail.Module.scss';
import {
  Card,
  Image,
  List,
  Popover,
  Space,
  Tag,
  Typography
  , Button, message, Spin, Empty, Popconfirm,
} from 'antd';
import {getFullCoverURL, getPercentile} from '../utils/convert';
import {
  CalendarOutlined, CommentOutlined,
  LinkOutlined,
  PayCircleOutlined, StarOutlined, LineChartOutlined,
} from '@ant-design/icons';
import {ProductDetail} from './ProductDetail';
import {SourceLogo} from './SourceLogo';
import {Link} from 'react-router-dom';
import {getProductInfo, postSearchKey} from '../network/requests';
import {Column} from '@ant-design/charts';
import {usePrefersColorScheme} from '@anatoliygatt/use-prefers-color-scheme';

export function OuterLink({text, link, disabled}) {
  if (disabled) {
    return <Typography.Text className={style.disabled} type={'secondary'}>
      <Space>
        <LinkOutlined/>{text}
      </Space>
    </Typography.Text>;
  }
  return (<a target={'_blank'} href={link} rel="noreferrer">
    <Space>
      <LinkOutlined/>{text}
    </Space>
  </a>);
}

function ProductList(props) {
  const {list, text}=props;
  let content;
  if (!list) {
    content=<Spin spinning={true}/>;
  } else if (list.length) {
    content=list.map((book)=><ProductDetail key={book.id} {...book}/>);
  } else {
    content=<Empty size={'small'}/>;
  }
  return <Popover
    trigger={['click']}
    content={content}
    onClick={props.onClick}
    placement={'right'}
  >
    <a href={''}>{text}</a>
  </Popover>;
}

export const BookDetail=({book: item, small=false, statistics})=>{
  const [product, setProduct] = useState({});
  const prefersColorScheme = usePrefersColorScheme();
  const isDarkMode = prefersColorScheme === 'dark';
  const fetchProduct=useCallback(()=>{
    console.log(Object.keys(product));
    if (Object.keys(product).length) {
      return;
    }
    getProductInfo(item.isbn).then((data)=>{
      setProduct(data);
    }).catch(()=>{
      message.error('获取商品列表失败');
    });
  });

  const getDistConfig=(dist)=>{
    const itemValue=dist.name==='publish_date'? Number(new Date(item.publish_date))/1000:item[dist.name];
    return {
      padding: 'auto',
      appendPadding: [12, 16, 8, 16],
      theme: isDarkMode?'dark':'default',
      meta: {
        key: {alias: dist.displayName, type: dist.useLog?'log': 'linear'},
        value: {alias: '数量'},
      },
      data: dist.data,
      xField: 'key',
      yField: 'value',
      xAxis: {
        title: null,
        label: {
          formatter: (date)=>{
            if (dist.name==='publish_date') {
              return new Date(date*1000).getFullYear();
            }
            return date;
          },
        },
      },
      yAxis: {
        title: null,
      },
      maxColumnWidth: dist.useLog?undefined:Math.max(1, 200/dist.segments*1.1),
      minColumnWidth: dist.useLog?undefined:Math.max(1, 200/dist.segments*1.1),
      width: 200,
      height: 150,
      annotations: [
        {
          type: 'line',
          start: [itemValue, 'min'],
          end: [itemValue, 'max'],
          text: {
            content: getPercentile(dist.data, itemValue),
            position: 'right',
            offsetX: 18,
            offsetY: 8,
            style: {
              textAlign: 'right',
            },
          },
          style: {
            lineDash: [2, 2],
          },
        },
      ],
    };
  };

  return (
    <Card
      bordered={false}
      className={style.outerCard}
      title={<>
        <Typography.Text copyable strong>
          {item.name}
        </Typography.Text>
        {
          item.min_idx<100 &&
          <Tag
            className={style.statusIcon}
            color='green'
          >最高排名 {item.min_idx}
          </Tag>
        }
        {
          item.mention>1 &&
          <Tag
            className={style.statusIcon}
            color='geekblue'
          >出现 {item.mention} 次
          </Tag>
        }
      </>}
    >
      <List.Item
        style={{padding: 0}}
        key={item.id}
        actions={[
          item.jd_id?
            <OuterLink disabled={!item.jd_id} key={1} text={<SourceLogo source={'jd'} noMargin={true}/>} link={`https://item.jd.com/${item.jd_id}.html`}/>:
            <ProductList onClick={fetchProduct} list={product.unique_jd_books} text={<SourceLogo source={'jd'} noMargin={true}/>}/>,
          item.dd_id?
            <OuterLink disabled={!item.dd_id} key={2} text={<SourceLogo source={'dd'} noMargin={true}/>} link={`http://product.dangdang.com/${item.dd_id}.html`}/>:
            <ProductList onClick={fetchProduct} list={product.unique_dd_books} text={<SourceLogo source={'dd'} noMargin={true}/>}/>,
          <OuterLink key={3} text={'豆瓣'} link={`https://book.douban.com/isbn/${item.isbn}`}/>,
          <OuterLink key={4} text={'国家图书馆'}
            link={`http://opac.nlc.cn/F/?func=find-m&request=${item.isbn}&find_code=ISB`}/>,
          small?
                <Popconfirm onConfirm={()=>{
                  postSearchKey({
                    maxCount: 0,
                    platform: ['comment'],
                    key: item.isbn,
                  }).then(()=>{
                    message.success('创建成功');
                  }).catch(()=>{
                    message.error('创建失败');
                  });
                }} title={'爬取这本书的评论？'}>
                  <Button
                    className={style.action}
                    size={'small'} type={'link'}
                    icon={<CommentOutlined/>}>爬取评论</Button>
                </Popconfirm>:
              <Link
                key={5}
                to={'/comments?query=' + encodeURIComponent(item.isbn)}>
                <Button
                  className={style.action}
                  size={'small'} type={'link'}
                  icon={<CommentOutlined/>}
                >评论分析页面</Button>
              </Link>,
          statistics && <Popover trigger={['click']} content={<div className={style.graphContainer}>
            {statistics.distribution.map((dist)=>
              <div key={dist.name}>
                <Column className={style.graph} {...getDistConfig(dist)}/>
                <Typography.Text type={'secondary'} className={style.graphName}>{dist.displayName}{dist.useLog && ' (Log)'}</Typography.Text>
              </div>)}
          </div>} key={6}>
            <Button
              className={style.action+' '+style.statistics} size={'small'} type={'link'} icon={<LineChartOutlined/>}>查看数据分布</Button>
          </Popover>,
        ]}
      >
        <div className={style.card}>

          <Image
            className={style.cover+' '+(small?style.small:'')}
            src={getFullCoverURL(item.cover)}
          />
          <div className={style.desc}>
            {[
              ['作者', item.author],
              ['译者', item.translator],
              ['出版社', item.publisher],
              ['出版时间', item.publish_date, <CalendarOutlined key={'icon'}/>],
              ['ISBN', item.isbn],
              ['价格',
                item.min_p?`${item.min_p} ~ ${item.max_p} 平均 ${item.avg_p}`:'',
                <PayCircleOutlined key={'icon'}/>,
              ],
            ].map(
                ([key, val, icon]) =>
              val ?
                <div key={key} className={style.descLine}>
                  <Typography.Text
                    className={style.key}
                    type={'secondary'}
                  >
                    {key}
                  </Typography.Text>
                  {icon && <Typography.Text className={style.icon}>
                    {icon}
                  </Typography.Text>}
                  <Typography.Text className={style.val}>
                    <Popover
                      content={
                        <Typography.Text copyable>
                          {val}
                        </Typography.Text>
                      }>
                      {val}
                    </Popover>
                  </Typography.Text>
                </div> : null,
            )}
            <Space className={style.descLine}>
              {item.comment_count &&
                  <>
                    <CommentOutlined/>
                    {item.comment_count}
                  </>
              }
              {item.average_score &&
                <>
                  <StarOutlined/>
                  {Number(item.average_score).toFixed(2)}
                </>
              }
            </Space>
          </div>
          <div
            className={style.digest+' '+(small?style.small:'')}
            dangerouslySetInnerHTML={{__html: item.digest}}
          />
        </div>
      </List.Item>
    </Card>);
};
